<template>
  <div class="update-profile-page m-auto">
    <!-- tab切换 -->
    <ul class="nav nav-tabs nav-fill mb-4" id="myTab" role="tablist">
      <li class="nav-item ">
        <a
          href="#"
          :class="generateActiveClass('profile')"
          @click.prevent="switchTab('profile')"
        >
          更新个人资料
        </a>
      </li>
      <li class="nav-item">
        <a
          href="#"
          :class="generateActiveClass('column')"
          @click.prevent="switchTab('column')"
        >
          更新专栏资料
        </a>
      </li>
    </ul>
    <!-- tab内容 -->
    <div class="tab-content">
      <uploader
        action="/upload"
        class="d-flex align-items-center justify-content-center bg-light text-secondary circle mx-auto my-3"
        :beforeUpload="commonUploadCheck"
        :uploaded="uploadedData"
        @file-uploaded="onFileUploaded"
      >
        <template #loading>
          <div class="d-flex">
            <div class="spinner-border text-secondary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
            <h2>正在上传</h2>
          </div>
        </template>
        <template v-slot:uploaded="dataProps">
          <img
            :src="
              dataProps.uploadedData.data.url +
                '?x-oss-process=image/resize,m_fill,h_200,w_200'
            "
          />
        </template>
        <h3>点击上传头像</h3>
      </uploader>
      <validate-form ref="formRef" @form-submit="onFormSubmit">
        <div class="mb-3">
          <label class="form-label">
            {{ currentCategory === "profile" ? "用户名" : "专栏名" }}</label
          >
          <validate-input
            :rules="nameRules"
            placeholder="请输入名称"
            v-model="nameValue"
            type="text"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">
            {{ currentCategory === "profile" ? "个人简介" : "专栏简介" }}</label
          >
          <validate-input
            :rules="descRules"
            placeholder="请输入简介信息"
            v-model="descValue"
            rows="5"
            tag="textarea"
          />
        </div>
        <template #submit>
          <button class="btn btn-primary btn-large">
            {{
              currentCategory === "profile" ? "提交个人资料" : "提交专栏资料"
            }}
          </button>
        </template>
      </validate-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, watch } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ResponseType, ImageProps } from "@/store";
import Uploader from "../components/Uploader.vue";
import ValidateInput, { RulesProp } from "../components/ValidateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import createMessage from "../components/createMessage";
import { commonUploadCheck } from "../helper";
type EditCategory = "profile" | "column" | "init";
export default defineComponent({
  name: "EditDetail",
  components: {
    Uploader,
    ValidateInput,
    ValidateForm
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    // 当前 tab的类型 profile说明是用户资料 column说明是专栏信息
    const currentCategory = ref<EditCategory>("init");
    // 设置当前的class样式
    const generateActiveClass = (klass: EditCategory) => {
      return {
        active: currentCategory.value === klass,
        "nav-link": true
      };
    };
    // 获取用户信息
    const userStore = computed(() => {
      return store.state.user;
    });
    // 获取专栏的信息
    const currentColumn = computed(() => {
      return store.getters.getColumnById(userStore.value.column);
    });
    const uploadedData = ref();
    // 切换tab页的时候需要
    watch(currentCategory, () => {
      if (currentCategory.value === "profile") {
        if (userStore.value && userStore.value.avatar) {
          const { avatar } = userStore.value;
          uploadedData.value = { data: avatar };
        }
      } else {
        if (currentColumn.value && currentColumn.value.avatar) {
          const { avatar } = currentColumn.value;
          uploadedData.value = { data: avatar };
        } else {
          uploadedData.value = null;
        }
      }
    });
    // 用户名 和 简介
    const nameValue = ref(userStore.value && userStore.value.nickName);
    const descValue = ref(userStore.value && userStore.value.description);
    // 切换专栏信息的 点击事件
    const switchTab = (which: EditCategory) => {
      currentCategory.value = which;
      if (which === "column" && currentColumn.value) {
        const { title, description } = currentColumn.value;
        nameValue.value = title;
        descValue.value = description;
      } else {
        const { nickName, description } = userStore.value;
        nameValue.value = nickName;
        descValue.value = description;
      }
    };

    // 上来的时候先显示用户tab
    onMounted(() => {
      currentCategory.value = "profile";
      // 获取到用户的columnid之后 发起异步请求
      const cid = userStore.value.column;
      if (cid) {
        store.dispatch("fetchColumn", cid);
      }
    });
    let imageId = "";
    const nameRules: RulesProp = [
      { type: "required", message: "名字不能为空" }
    ];
    const descRules: RulesProp = [
      { type: "required", message: "详情不能为空" }
    ];
    // 上传文件之后 预览图片
    const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id;
      }
    };
    const onFormSubmit = (result: boolean) => {
      if (result) {
        let payload: any = {};
        // 提交的是个人资料tab的表单
        if (currentCategory.value === "profile") {
          payload = {
            _id: userStore.value._id,
            nickName: nameValue.value,
            description: descValue.value
          };
        } else {
          payload = {
            _id: currentColumn.value._id,
            title: nameValue.value,
            description: descValue.value
          };
        }
        if (imageId) {
          payload.avatar = imageId;
        }
        const actionName =
          currentCategory.value === "profile" ? "updateUser" : "updateColumn";
        const sendData =
          currentCategory.value === "profile"
            ? {
                id: userStore.value._id,
                payload
              }
            : {
                id: currentColumn.value._id,
                payload
              };
        store.dispatch(actionName, sendData).then(() => {
          // createMessage("修改成功，2秒后跳转到首页", "success", 2000);
          createMessage("修改成功", "success", 2000, "跳转到首页");
          setTimeout(() => {
            router.push("/");
          }, 2000);
        });
      }
    };
    // const showTab = ref("user");
    // const changeTab = flag => {
    //   showTab.value = flag;
    // };
    return {
      generateActiveClass,
      switchTab,
      onFileUploaded,
      uploadedData,
      onFormSubmit,
      commonUploadCheck,
      nameRules,
      descRules,
      nameValue,
      descValue,
      currentCategory
      // showTab,
      // changeTab
    };
  }
});
</script>

<style lang="less">
.update-profile-page {
  width: 700px;
  // background-color: @Bg_blue1;
}
// 注意：这里想要传递给组件的样式class不能添加scoped
.circle {
  width: 200px;
  height: 200px;
  border-radius: 200px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #efefef;
}
</style>
